//
//  ComposeViewController.swift
//  XMGWB
//
//  Created by xiaomage on 15/11/16.
//  Copyright © 2015年 xiaomage. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    // MARK:- 属性
    /// 工具条底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
    // 容器视图,高度约束
    @IBOutlet weak var containerViewHeightCons: NSLayoutConstraint!
    
    /// 自定义TextView
    @IBOutlet weak var statusTextView: ComposeTextView!
    
    /// 显示当前剩余可以输入多少文字的Label
    @IBOutlet weak var tipLabel: UILabel!
    
    /// 容器视图中的控制器
    private var photoPickerVc : PhotoPickerViewController?
    
    // 规定最大输入的数字
    let maxCount = 140
    
    // 懒加载表情控制器
    lazy var keyboardEmoticonVc : XMGKeyboardEmoticonViewController = XMGKeyboardEmoticonViewController {[unowned self] (emoticon) -> () in
        self.statusTextView.insertEmoticon(emoticon)
        
        // 当插入表情时,主动出发文字改变的代理
        self.textViewDidChange(self.statusTextView)
    }
    
    // MARK:- 监听按钮的点击
    /// 监听图片按钮的点击
    @IBAction func pictureBtnClick(sender: AnyObject) {
        // 1.设置约束
        self.containerViewHeightCons.constant = UIScreen.mainScreen().bounds.height * 0.7
        
        // 2.执行动画
        UIView.animateWithDuration(0.4) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        // 3.退出键盘
        self.statusTextView.resignFirstResponder()
    }
    /// 监听表情按钮点击
    @IBAction func emoticonBtnClick(sender: AnyObject) {
        // 1.退出键盘
        self.statusTextView.resignFirstResponder()
        
        // 2.切换键盘
        if self.statusTextView.inputView == nil { // 普通键盘,需要切换表情键盘
            self.statusTextView.inputView = keyboardEmoticonVc.view
        } else { // 表情键盘,需要切换成普通键盘
            self.statusTextView.inputView = nil
        }
        
        // 3.弹出键盘
        self.statusTextView.becomeFirstResponder()
    }
    
    /// 监听取消按钮的点击
    @IBAction func cancleBtnClick(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 监听发送按钮点击
    @IBAction func sendBtnClick(sender: AnyObject) {
        // 1.获取发送微博的内容
        let emoticonStr = self.statusTextView.emoticonStr()
        
        // 2.显示正在发送
        SVProgressHUD.showWithStatus("正在发送", maskType: SVProgressHUDMaskType.Black)
        
        // 3.获取用户选中的图片
        let image = photoPickerVc?.images.first
        
        // 4.发送微博
        NetworkTools.shareInstance.sendStatus(emoticonStr, image: image) { (dict, error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("发送微博失败", maskType: SVProgressHUDMaskType.Black)
            } else {
                SVProgressHUD.showInfoWithStatus("发送微博成功", maskType: SVProgressHUDMaskType.Black)
            }
            
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
        // 5.退出键盘
        self.statusTextView.resignFirstResponder()
    }
    
    
    
    // MARK:- 系统调用的方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.设置textView代理
        statusTextView.delegate = self
        
        // 2.监听键盘变化
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillChange:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 3.设置容器视图的高度
        self.containerViewHeightCons.constant = 0
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if containerViewHeightCons.constant == 0 {
            // 召唤键盘
            statusTextView.becomeFirstResponder()
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        // 注销键盘
        statusTextView.resignFirstResponder()
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        segue.destinationViewController
        if segue.identifier == "compose2photopicker" {
            photoPickerVc = segue.destinationViewController as? PhotoPickerViewController
        }
    }
    
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    
    // MARK: - 内部控制方法
    @objc private func keyboardWillChange(note: NSNotification)
    {
        // 获取键盘弹出和退出的时间
        let durationTime = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        
        // 获取和底部的差距
        let endFrame = note.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue;
        let margin = view.frame.size.height - endFrame.origin.y
        
        // 改变约束,并且执行动画
        toolbarBottomCons.constant = margin
        UIView.animateWithDuration(durationTime) { () -> Void in
            // 如果执行多次动画,则忽略上一次已经未完成的动画,直接进入下一次
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!)
            self.view.layoutIfNeeded()
        }
    }

}





extension ComposeViewController: UITextViewDelegate
{
    func textViewDidChange(textView: UITextView) {
        // 判断按钮的状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        self.statusTextView.placeholderLabel.hidden = textView.hasText()
        
        // 判断文字的多少
        let currentCount = self.statusTextView.emoticonStr().characters.count
        
        // 设置显示的数字
        tipLabel.text = "\(maxCount - currentCount)"
        
        // 判断发送按钮是否可以点击
        navigationItem.rightBarButtonItem?.enabled = (maxCount - currentCount) >= 0 ? true : false
        tipLabel.textColor = (maxCount - currentCount) >= 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        statusTextView.resignFirstResponder()
    }
}
